package com.example.androidcomplete0102.ch19;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.androidcomplete0102.R;

public class LongTime5 extends Activity {
	int mValue;
    TextView mText;
    ProgressDialog mProgress;
    public static final String TAG="ASYNCTASK";
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ch19_uploadex);
        mText=(TextView)findViewById(R.id.ch19_text);
    }
    
    public void mOnClick(View v){
    	Log.d(TAG, "onClick");
    	new AccumulateTask().execute(100);
    }
    
    class AccumulateTask extends AsyncTask<Integer, Integer, Integer>{
    	@Override
    	protected void onPreExecute() {
    		Log.d(TAG, "onPreExecute()");
    		super.onPreExecute();
    		mProgress =new ProgressDialog(LongTime5.this);
            mProgress.setTitle("Updating");
            mProgress.setMessage("Wait...");
            mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgress.setProgress(0);
            mProgress.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					cancel(true); 					
				}
			});
            mProgress.show();
    	}
    	
    	@Override
    	protected void onCancelled() {
    		Log.d(TAG, "onCancelled() : ");
    		mProgress.dismiss();
    	}
    	
		protected Integer doInBackground(Integer... params) {
			Log.d(TAG, "doInBackground() : "+params[0]);
			while(isCancelled() == false){
				mValue++;
				if (mValue <= 100){
					publishProgress(mValue);
				}else{
					break;
				}
				try {Thread.sleep(50);} catch (InterruptedException e) {}
			}
			return mValue;
		}
    	 @Override
    	protected void onProgressUpdate(Integer... values) {
    		Log.d(TAG, "onProgressUpdate() " + values[0]);
    		mProgress.setProgress(values[0]);
    		mText.setText(Integer.toString(values[0]));
    	}
    	 
    	 @Override
    	protected void onPostExecute(Integer result) {
    		Log.d(TAG, "onPostExecute() " + result);
    		mProgress.dismiss();
    		mValue = 0;
    	}
    }
}
